package com.ams.config;

import com.ams.dao.AttendanceMapper;
import com.ams.dao.EmployeeInformationMapper;
import com.ams.dao.LeaveTableMapper;
import com.ams.pojo.Attendance;
import com.ams.pojo.EmployeeInformation;
import com.ams.pojo.LeaveTable;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class SaticScheduleTask {
    @Autowired(required = false)
    AttendanceMapper attendanceMapper;
    @Autowired(required = false)
    EmployeeInformationMapper employeeInformationMapper;
    @Autowired(required = false)
    LeaveTableMapper leaveTableMapper;


    //3.添加定时任务
    //每天定时插入考勤人员数据
    @Scheduled(cron = "0 58 10 * * ?")//(秒  分  时  日  月  星期  年)
    private void everyInsert() {
        List<EmployeeInformation> emp = employeeInformationMapper.selectList(null);
        SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd");
        //查询今天有哪些人请假，出差
        List<LeaveTable> leaveTables = leaveTableMapper.selectToDay();
        for (EmployeeInformation e:emp){
            Attendance a = new Attendance();
            a.setStaffId(e.getStaffId());
            //判断请假，出差名单中是否有此人，有就加上备注
            for (LeaveTable l:leaveTables){
                if (a.getStaffId().equals(l.getStaffId())){
                    a.setRemarks(l.getLeaveType());
                }
            }
            a.setDepartment(e.getDepartment());
            a.setStaffName(e.getStaffName());
            a.setClockDate(simp.format(new Date()));
            System.out.println("===================" + a);
            attendanceMapper.insert(a);
        }
    }

    //每天定时判断人员是否缺勤
    @Scheduled(cron = "0 0 20 * * ?")//(秒  分  时  日  月  星期  年)
    private void everyUppdate() {
        SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd");
        QueryWrapper<Attendance> queryWrapper = new QueryWrapper<>();
        //查询今天的考勤信息
        queryWrapper.eq("clock_date",simp.format(new Date()));
        List<Attendance> attendances = attendanceMapper.selectList(queryWrapper);
        for (Attendance a:attendances){
            if (a.getRemarks()==null){
                //判断此人今天是否有上班打卡，无就证明今天缺勤
                if(a.getClockInTime()==null){
                    a.setRemarks("缺勤");
                }
                attendanceMapper.updateById(a);
            }
        }
    }
}

